//
//  RCFansListVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-8-22.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCFansListVC.h"
#import "RCUserVCOrderListCell.h"
#import "RCMerchantListCell.h"
#import "RCMerchantsListDataModel.h"
#import "RCUserVCFansListCell.h"
#import "RCUserVCMyCheckInCell.h"
#import "RCUserVCMyPhotosCell.h"
#import "UIImageView+Extented.h"
#import "CommonDefines.h"
#import "IManager+ModulePersonCenter.h"
#import "RCMyPhotosListDataModel.h"
#import "RCUserVC.h"
#import "RCMerchantDetailVC.h"
#import "RCUserScoreCell.h"
#import "RCServerPhotoCheckCell.h"
#import "RCServerCheckPhotoListModel.h"
#import "RCMemberCardSuccessTakeVC.h"
#import "AppDelegate.h"
#import "UIColor-Expanded.h"
#import "RCTopListTypeDataModel.h"
#import "RCToplistTypeView.h"
#import "RCMessageListDataModel.h"


#define kHeaderTitleImageFile          @"image_topList_headerView_button.png"


@interface RCFansListVC ()<IManagerDelegate,RCFoorGoodsProtocol,RCPhotoCheckProtocol,RCToplistTypeViewDelegate>{
    RCBaseListDataModel *_model;
    int64_t  _reqID;
    BOOL     _refresh;
    int      _pn;
    
    NSString  *_orderType;
    
    NSString *_userID; //other user;
}
@property (nonatomic, retain) RCBaseListDataModel *model;
@property (nonatomic,retain) MBProgressHUDEx *progressHub;
@property(nonatomic,retain) UIButton *headerTitleButton;
@property(nonatomic,retain) UILabel *headerTitleLabel;
@property(nonatomic,retain) RCToplistTypeView *typeListView;
@property(nonatomic,retain) UIButton *transparentButton;
@property (nonatomic, retain) NSString *orderType;

@end

@implementation RCFansListVC

@synthesize vcType = _vcType;
@synthesize model = _model;
@synthesize progressHub = _progressHub;
@synthesize headerTitleButton = _headerTitleButton;
@synthesize headerTitleLabel = _headerTitleLabel;
@synthesize typeListView = _typeListView;
@synthesize transparentButton = _transparentButton;
@synthesize orderType = _orderType;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (id) initWithUserID:(NSString *)userID
{
    self = [super init];
    if (self) {
        _userID  = [userID copy];
    }
    return self;
}

- (void) dealloc
{
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_reqID];
    self.progressHub.delegate = nil;
    self.orderType = nil;
    self.progressHub = nil;
    self.typeListView = nil;
    self.headerTitleLabel = nil; self.headerTitleButton = nil;
    [_model release];
    [_userID release];
    [super dealloc];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
   
    
    UIButton *rightBtn = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)] autorelease];
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0f) {
        rightBtn.frame = CGRectMake(10, 0, 44, 44);
    }

    if (_vcType == FansListVCType_fans) {
        self.titleLabelText = @"我的粉丝";
        [rightBtn setImage:[UIImage imageNamed:@"RightIcon_RCUserVC_Fans"] forState:UIControlStateNormal];

    }else if(_vcType == FansListVCType_follow){
        self.titleLabelText = @"我的关注";
        [rightBtn setImage:[UIImage imageNamed:@"RightIcon_RCUserVC_Follow"] forState:UIControlStateNormal];
    }else if(_vcType == FansListVCType_myCheckIn){
        self.titleLabelText = @"我的签到";
//        [rightBtn setImage:[UIImage imageNamed:@"RightIcon_RCUserVC_Dianping"] forState:UIControlStateNormal];
    }else if(_vcType == FansListVCType_myCollect){
        self.titleLabelText = @"收藏";
        [rightBtn setImage:[UIImage imageNamed:@"RightIcon_RCUserVC_Collect"] forState:UIControlStateNormal];
    }else if (_vcType == FansListVCType_myOrders){
        self.titleLabelText = @"我的订单";
        [rightBtn setImage:[UIImage imageNamed:@"RightIcon_RCUserVC_Order"] forState:UIControlStateNormal];
    }else if (_vcType == FansListVCType_dianping){
        self.titleLabelText = @"我的点评";
        [rightBtn setImage:[UIImage imageNamed:@"RightIcon_RCUserVC_Dianping"] forState:UIControlStateNormal];
    }else if (_vcType == FansListVCType_photo){
        self.titleLabelText = @"我的照片";
        [rightBtn setImage:[UIImage imageNamed:@"RightIcon_RCUserVC_Dianping"] forState:UIControlStateNormal];
    }else if (_vcType == FansListVCType_Score){
        self.titleLabelText = @"积分商城";
    }else if (_vcType == FansListVCType_photoCheck){
        self.titleLabelText = @"图片审核";
    }else if (_vcType == FansListVCType_mailBox){
        self.titleLabelText = @"私信列表";
    }

    self.navigationItem.titleView = [self createTitleView];
    
    self.navigationItem.rightBarButtonItem = [self createRightBarButtonItemWithButton:rightBtn];

    if (_vcType == FansListVCType_myOrders) {
        [self createTitleButtonView];
    }
    
    // 设置tableview相关参数
    if ( baseVCTableView != nil ) {
        self.view.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
//        baseVCTableView.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.backgroundColor = [UIColor clearColor];
        baseVCTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        baseVCTableView.frame = self.view.bounds;
        CGRect tableViewNewFrame  = CGRectMake(baseVCTableView.frame.origin.x,baseVCTableView.frame.origin.y,baseVCTableView.frame.size.width,UIScreenHeight-20-self.navigationController.navigationBar.frame.size.height-4);
      
        baseVCTableView.frame = tableViewNewFrame;
        baseVCTableView.tableHeaderView = nil;
        baseVCTableView.tableFooterView = nil;
        [self addPullRefresh];
    }
    [self refreshData];
}

-(void)createTitleButtonView{
    _headerTitleButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 157, 36)];
    _headerTitleButton.backgroundColor = [UIColor clearColor];
    [_headerTitleButton addTarget:self action:@selector(headerTitleButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [_headerTitleButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kHeaderTitleImageFile ofType:nil]] forState:UIControlStateNormal];
    
    _headerTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 90, 16)];
    _headerTitleLabel.backgroundColor = [UIColor clearColor];
    _headerTitleLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    _headerTitleLabel.textColor = [UIColor whiteColor];
    [_headerTitleButton addSubview:_headerTitleLabel];
    _headerTitleLabel.text =@"商户预订";
    self.navigationItem.titleView = _headerTitleButton;
    self.orderType = @"shoporder";
    
    
    
    RCTopListTypeDataModel *model = [[RCTopListTypeDataModel alloc] init];
    NSMutableArray *mutArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < 5; i ++) {
        RCTopListTypeCategoryItem *item = [[RCTopListTypeCategoryItem alloc] init];
        if (i == 0) {
            item.categoryID = @"shoporder";
            item.categoryName = @"商户预订";
        }else if (i == 1){
            item.categoryID = @"cardorder";
            item.categoryName = @"会员卡领认";
        }else if (i == 2){
            item.categoryID = @"scoreorder";
            item.categoryName = @"积分兑换";
        }else if (i == 3){
            item.categoryID = @"discountorder";
            item.categoryName = @"优惠报名";
        }else if (i == 4){
            item.categoryID = @"ticketorder";
            item.categoryName = @"票务预订";
        }
        [mutArr addObject:item];
        [item release];
    }
    model.categoryListArray = mutArr;
    [mutArr release];
    
    _typeListView = [[RCToplistTypeView alloc]initWithFrame:CGRectMake(0, 0, 320, 260) andDataSource:model];
    _typeListView.delegate = self;
    _typeListView.hidden = YES;
    [self.view addSubview:_typeListView];
    
    _transparentButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 260, 320, UIScreenHeight-64-260)];
    
    _transparentButton.backgroundColor = [UIColor colorWithHex:0x77000000];
    [_transparentButton addTarget:self action:@selector(transparentButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    _transparentButton.hidden = YES;
    [self.view addSubview:_transparentButton];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark TableView Refresh And LoadMore
- (void) refreshData
{
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    _refresh = YES;
    _pn = 0;
    
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_reqID];
    
    _reqID = [[IManager sharedInstance] requestFansListData:_vcType withPn:0 withRn:10 withUserID:_userID withStatus:self.orderType withDelegte:self];

    
}



- (void) loadMoreData
{
    _refresh = NO;
    
//    NSString *page = [NSString stringWithFormat:@"%d",_pn];
    _reqID = [[IManager sharedInstance] requestFansListData:_vcType withPn:_pn withRn:10 withUserID:_userID withStatus:self.orderType withDelegte:self];
}


#pragma mark UITableView Datasource & Delegate

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_vcType == FansListVCType_photo) {
        return (([self.model.listItems count] +1) / 2);
    }else if (_vcType == FansListVCType_myOrders){
        return [self.model.listItems count];
    }
    return [self.model.listItems count];
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_vcType == FansListVCType_myOrders) {
        return 95;
    }else if (_vcType == FansListVCType_myCollect){
        return 100;
    }else if (_vcType == FansListVCType_fans || _vcType == FansListVCType_follow ||_vcType== FansListVCType_Score){
        return 80;
    }else if ( _vcType == FansListVCType_dianping){
        return 115+kHeadHeight;
    }else if (_vcType == FansListVCType_photo){
        return 145;
    }else if (_vcType == FansListVCType_myCheckIn ){
        return 115;
    }else if (_vcType == FansListVCType_photoCheck ){
        return 110;
    }
    return 40;
}


- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(_vcType == FansListVCType_fans || _vcType == FansListVCType_follow){
        UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 25)]autorelease];
        headerView.backgroundColor = [UIColor colorWithRed:194.0/255 green:194.0/255 blue:194.0/255 alpha:1];
        UILabel *t = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 100, 15)];
        [headerView addSubview:t];
        [t setTextColor:[UIColor whiteColor]];
        t.font = [UIFont fontWithName:kFontNameHelvetica size:12];
        t.backgroundColor = [UIColor clearColor];
        if (_vcType == FansListVCType_follow) {
            t.text = [NSString stringWithFormat:@"关注了%d位",[self.model.listItems count]];
        }else{
            t.text = [NSString stringWithFormat:@"有%d位粉丝",[self.model.listItems count]];
        }
        [t release];
   
        
        return headerView;
    }else{
        return nil;
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   if(_vcType == FansListVCType_fans || _vcType == FansListVCType_follow){
        return 20;
    }else{
        return 0;
    }
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if (_vcType == FansListVCType_myOrders) {
        //我的订单
        cell = [tableView dequeueReusableCellWithIdentifier:@"RCUserOrderListCell"];
        if (nil == cell) {
            cell = [[[RCUserOrderListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RCUserVCOrderListCell"] autorelease];
        }
        RCMyOrderItemDataModel *item = [self.model.listItems objectAtIndex:([indexPath row])];

        [(RCUserOrderListCell *)cell bindData:item];
        return cell;
    }else if (_vcType == FansListVCType_myCollect){
        //我的收藏
        NSString *cellID = @"RCMerchantListCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[RCMerchantListCell alloc] init] autorelease];
        }
        RCMerchant *merchant = [self.model.listItems objectAtIndex:[indexPath row]];

        [(RCMerchantListCell*)cell bindData:merchant];
        return cell;
        
    }else if (_vcType == FansListVCType_follow || _vcType == FansListVCType_fans){
        //我的粉丝、我的关注
        NSString *cellID = @"RCUserVCFansListCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[RCUserVCFansListCell alloc] init] autorelease];
        }
        RCFansFollowerItemDataModel *item = [self.model.listItems objectAtIndex:[indexPath row]];
        [(RCUserVCFansListCell *)cell bindData:item];
        return cell;
    }else if (_vcType == FansListVCType_myCheckIn || _vcType == FansListVCType_dianping){
        //我的签到、点评
        NSString *cellID = @"RCUserVCMyCheckInCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        BOOL needHeader = NO;
        if (_vcType == FansListVCType_dianping) {
            needHeader = YES;
        }
        if (cell == nil) {
            cell = [[[RCUserVCMyCheckInCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID withHeader:needHeader]autorelease];
        }
        RCDianpingItemDataModel *item = [self.model.listItems objectAtIndex:[indexPath row]];
        [(RCUserVCMyCheckInCell *)cell bindData:item];
        return cell;
    }else if (_vcType == FansListVCType_photo){
        NSString *cellID = @"RCUserVCMyPhotosCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[RCUserVCMyPhotosCell alloc] init] autorelease];
        }
        RCMyPhotosItemDataModel *leftItem = [self.model.listItems objectAtIndex:[indexPath row]*2];
        RCMyPhotosItemDataModel *rightItem = nil;
        if ([self.model.listItems count] > [indexPath row]*2+1) {
            rightItem = [self.model.listItems objectAtIndex:([indexPath row]*2+1)];
        }

        [(RCUserVCMyPhotosCell *)cell bindData:leftItem withRight:rightItem];
        return cell;
    }else if (_vcType == FansListVCType_Score){
        NSString *cellID = @"RCUserScoreCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[RCUserScoreCell alloc] init] autorelease];
        
        }
        RCScoreListItemDataModel *leftItem = [self.model.listItems objectAtIndex:[indexPath row]];
        [(RCUserScoreCell *)cell  bindData:leftItem];
        [(RCUserScoreCell *)cell setDelegate:self];
        
//        [(RCUserVCMyPhotosCell *)cell bindData:leftItem withRight:rightItem];
        return cell;
    }else if (_vcType == FansListVCType_photoCheck){
        NSString *cellID = @"RCServerPhotoCheckCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[RCServerPhotoCheckCell alloc] init] autorelease];
        }
        RCServerCheckPhotoItemModel *item = [self.model.listItems objectAtIndex:[indexPath row]];
        [(RCServerPhotoCheckCell *)cell  bindData:item];
        [(RCServerPhotoCheckCell *)cell setDelegate:self];

        //        [(RCUserVCMyPhotosCell *)cell bindData:leftItem withRight:rightItem];
        return cell;
    }else if (_vcType == FansListVCType_mailBox){
        NSString *cellID = @"RCMessageListCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] init] autorelease];
        }
        RCMessageListItemDataModel *item = [self.model.listItems objectAtIndex:[indexPath row]];
//        [(RCServerPhotoCheckCell *)cell  bindData:item];
//        [(RCServerPhotoCheckCell *)cell setDelegate:self];
        cell.textLabel.text = item.content;
        return cell;
    }
    cell = [[UITableViewCell alloc] init];
    if (_vcType == FansListVCType_fans) {
           cell.textLabel.text = @"我的粉丝";
    }else if (_vcType == FansListVCType_follow) {
           cell.textLabel.text = @"我的关注";
    }else if (_vcType == FansListVCType_myCollect) {
        cell.textLabel.text = @"收藏";
    }else{
        cell.textLabel.text = @"我的签到";

    }
 
    return [cell autorelease];
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_vcType == FansListVCType_fans || _vcType == FansListVCType_follow) {
        RCFansFollowerItemDataModel *item = [self.model.listItems objectAtIndex:[indexPath row]];

        RCUserVC *vc = [[RCUserVC alloc] initWithUserID:item.userID];
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }else if (_vcType == FansListVCType_myOrders){
//        RCMyOrderItemDataModel *item = [self.model.listItems objectAtIndex:[indexPath row]];
//        RCMerchantDetailVC *vc = [[RCMerchantDetailVC alloc] initWithMerchantID:item.shopID];
//        [self.navigationController pushViewController:vc animated:YES];
//        [vc release];
        
    }else if (_vcType == FansListVCType_myCollect){
        RCMerchant *merchant = [self.model.listItems objectAtIndex:[indexPath row]];
        RCMerchantDetailVC *vc = [[RCMerchantDetailVC alloc] initWithMerchantID:merchant.merchantID];
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }else if (_vcType == FansListVCType_myCheckIn || _vcType == FansListVCType_dianping){
        RCDianpingItemDataModel *item = [self.model.listItems objectAtIndex:[indexPath row]];
        RCMerchantDetailVC *vc = [[RCMerchantDetailVC alloc] initWithMerchantID:item.shopID];
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }else if (_vcType == FansListVCType_mailBox){
        RCMessageListItemDataModel *messageItem = [self.model.listItems objectAtIndex:[indexPath row]];
    }
    
}


#pragma mark Imanager Delegate


- (void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    if (_reqID == requestId) {
        if (_refresh) {
            [_progressHub removeFromSuperview];
            [_progressHub release];
            _progressHub = nil;
            [self finishRefreshingData];
            _refresh = NO;
        }else{
            [self finishLoadMoreData];
        }
    }
}

- (void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    if (dataModel.errorNO == RCErrorTypeNoError) {    
        RCBaseListDataModel *resultList = (RCBaseListDataModel *)dataModel;
        if (_refresh) {
            [_progressHub removeFromSuperview];
            [_progressHub release];
            _progressHub = nil;
            self.model = resultList;
            
//            [baseVCTableView reloadData];
            [self finishRefreshingData];
            _refresh = NO;
        }else{
            self.model.pn = resultList.pn;
            self.model.rn = resultList.rn;
            self.model.total = resultList.total;
            [self.model.listItems addObjectsFromArray:resultList.listItems];
            
            [baseVCTableView reloadData];
            [self finishLoadMoreData];
        }
        
        
        
        NSInteger currentTotal = [self.model.listItems count];
        _pn = currentTotal;
        
        if (currentTotal < self.model.total) {
            [self addPullLoadMore];
        }else{
            [self noMoreData];
        }
    }
    [baseVCTableView reloadData];
}

//积分商城 兑换物品是否成功
- (void) didGetGoodsSuccess:(BOOL)success withMessage:(NSString*)msg
{
    if (success) {
        RCMemberCardSuccessTakeVC *vc = [[RCMemberCardSuccessTakeVC alloc] initWithForGoods:YES];
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }else{
        [RCAppDelegate alertWithCustomizeString:msg];
    }
}


//图片审核 是否成功提交审核结果
-(void) photoStateDidSubmitSuccess:(BOOL)success withMsg:(NSString *)msg
{
    if (success) {
        //刷新数据
        [self refreshData];
        [RCAppDelegate alertWithCustomizeString:@"提交成功"];
    }else{
        [RCAppDelegate alertWithCustomizeString:msg];
    }
    
}




-(void)headerTitleButtonClicked{
    if (!_typeListView) {
        return;
    }
    if (_typeListView.hidden) {
        _typeListView.hidden = NO;
        _transparentButton.hidden = NO;
        [self.view bringSubviewToFront:_typeListView];
        [self.view bringSubviewToFront:_transparentButton];
    }else{
        _typeListView.hidden = YES;
        _transparentButton.hidden = YES;
    }
}


-(void)transparentButtonClicked{
    _typeListView.hidden = YES;
    _transparentButton.hidden = YES;
}


#pragma -mark ToplistTypeViewDelegate

-(void)selectToplistTypeItem:(RCTopListTypeCategoryItem *)item{
    _typeListView.hidden = YES;
    _transparentButton.hidden = YES;
    _headerTitleLabel.text = item.categoryName;
    self.orderType = item.categoryID;
    if (nil == item) {
        return;
    }
    [self refreshData];
}



@end
